package com.atguigu.myrule;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;

import java.util.List;

/**
 * 自定义Ribbon算法类
 * 共三个服务,每个服务连续使用5次,5次后换下一个服务,以此规律进行轮回
 */
public class MyRule  extends AbstractLoadBalancerRule {
    /**
     * 每次服务最大连续使用次数
     */
    private int total = 4;
    /**
     * 当前使用服务器编号
     */
    private int currentIndex = 0;

    /**
     * 服务器选择算法
     * @param lb
     * @param key
     * @return
     */
    public Server choose(ILoadBalancer lb, Object key) {
        if (lb == null) {
            return null;
        } else {
            Server server = null;
            while(server == null) {
                if (Thread.interrupted()) {
                    return null;
                }
                // 获取可用的服务
                List<Server> upList = lb.getReachableServers();
                List<Server> allList = lb.getAllServers();
                int serverCount = allList.size();
                if (serverCount == 0) {
                    return null;
                }
//              主要逻辑
                if (total > 0){
                    total --;
                }else{
                    total = 4;
                    ++ currentIndex;
                    if(currentIndex == upList.size()){
                        currentIndex = 0;
                    }
                }
                server = (Server)upList.get(currentIndex);
                if (server == null) {
                    Thread.yield();
                } else {
                    if (server.isAlive()) {
                        return server;
                    }
                    server = null;
                    Thread.yield();
                }
            }
            return server;
        }
    }
    @Override
    public Server choose(Object key) {
        return this.choose(this.getLoadBalancer(), key);
    }

    @Override
    public void initWithNiwsConfig(IClientConfig clientConfig) {}
}